<template>
  <div>
    <el-card>
      <div class="card-wrap">
        <el-page-header @back="goBack(false)" content="填报项目工时">
        </el-page-header>
        <div v-if="!isApproval">
          <el-button @click="goBack(false)">取消</el-button>
          <el-button
            type="primary"
            :loading="state.saveLoading"
            @click="handleSave(true, '1')"
            >保存
          </el-button>
          <el-button
            type="primary"
            :loading="state.saveLoading"
            @click="handleSubmit"
            >提交
          </el-button>
        </div>
      </div>
    </el-card>
    <br />
    <el-form
      :disabled="isApproval"
      :model="state.formData"
      ref="formRef"
      @submit.prevent
      :rules="formRules"
      label-width="80px"
    >
      <el-card>
        <template #header>
          <div class="card-box-header">
            <span>项目工时</span>
            <div v-if="show1" @click="show1 = !show1" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show1 = !show1" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>

        <el-collapse-transition>
          <div v-show="show1">
            <el-row :gutter="20">
              <el-col :xl="8" :lg="8">
                <el-form-item label="项目名称" prop="projectName">
                  <el-select
                    :disabled="source == 'back'"
                    v-model="state.formData.projectName"
                    clearable
                    style="width: 100%"
                    filterable
                    value-key="id"
                    @change="handleSelected"
                  >
                    <el-option
                      v-for="item in projectList"
                      :key="item.id"
                      :label="item.projectName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xl="8" :lg="8">
                <el-form-item label="项目编号">
                  <el-input
                    disabled
                    v-model.trim="state.formData.projectCode"
                    class="width-custom"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :xl="8" :lg="8">
                <el-form-item label="填报月份" prop="fillMonth">
                  <el-date-picker
                    :disabled="source == 'back'"
                    style="width: 100%"
                    v-model="state.formData.fillMonth"
                    value-format="YYYY-MM"
                    type="month"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xl="20" :lg="24">
                <el-form-item label="人员工时" prop="ext1">
                  <div class="work-tips">
                    <div>
                      <span class="left">填报人数</span>
                      <span>{{ state.formData.detailList?.length }}</span>
                    </div>

                    <div class="total">
                      <span class="left">工时总计</span>
                      <span>{{ quantityTotal }}</span>
                    </div>
                    <p>注：人员列表与项目成员一致</p>
                  </div>

                  <el-skeleton
                    style="height: 50vh"
                    :rows="8"
                    :loading="state.loading"
                    animated
                  >
                    <el-table
                      :data="state.formData.detailList"
                      border
                      style="width: 100%"
                      v-loading="state.loading"
                      :header-cell-style="{
                        background: '#eef1f6',
                        color: '#606266'
                      }"
                    >
                      <template #empty>
                        <el-empty
                          :image-size="150"
                          description="暂无数据"
                        ></el-empty>
                      </template>

                      <el-table-column type="index" label="序号" width="60">
                        <template v-slot="scope">
                          <span>{{
                            (pageNum - 1) * pageSize + scope.$index + 1
                          }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="userName"
                        label="姓名"
                      ></el-table-column>
                      <el-table-column
                        prop="belongOrg"
                        label="所属单位"
                        show-overflow-tooltip
                      ></el-table-column>
                      <el-table-column prop="projectTypeName" label="工时(天)">
                        <template #default="{ row }">
                          <el-input-number
                            v-model="row.quantity"
                            :min="0"
                            step="1"
                          />
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-skeleton>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-collapse-transition>
      </el-card>
      <br />
      <el-card v-if="route.query.instanceId">
        <template #header>
          <div class="card-box-header">
            <span> 流程状态</span>
            <div v-if="show5" @click="show5 = !show5" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show5 = !show5" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-if="steps && steps.length">
          <el-collapse-transition>
            <status-info :currentStep="currentStep" :steps="steps" />
          </el-collapse-transition>
        </div>
      </el-card>
      <br />
      <el-card v-if="route.query.instanceId">
        <template #header>
          <div class="card-box-header">
            <span> 流转记录</span>
            <div v-if="show6" @click="show6 = !show6" class="header-btn">
              收起
              <i class="el-icon-arrow-down"></i>
            </div>
            <div v-else @click="show6 = !show6" class="header-btn">
              展开
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </template>
        <div v-show="show6">
          <el-collapse-transition>
            <approval-info :activities="approveRecord" />
          </el-collapse-transition>
        </div>
      </el-card>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, unref, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { cloneDeep } from "lodash-es";
import {
  flowSubmit,
  flowStart,
  getApproveHistory,
  postProjectList,
  saveWorkingHour,
  workingHourDetails,
  getProjectInfo
} from "/@/api/project";

import NotifMessage from "/@/utils/message/notification";
import { storageLocal } from "/@/utils/storage";
import { flowStatusObj } from "/@/components/StatusInfo/type";
import StatusInfo from "/@/components/StatusInfo/index.vue";
import ApprovalInfo from "/@/components/ApprovalInfo/index.vue";

const steps = ref([]);
const formRef = ref<HTMLFormElement | null>(null) as any;
const approveRecord = ref([]);
const router = useRouter();
const route = useRoute();
let show1 = ref<boolean>(true);
let show5 = ref<boolean>(true);
let show6 = ref<boolean>(true);
let pageSize = 10;
let pageNum = 1;
const currentStep = ref(null);
let state: any = reactive({
  flowType: "2030",
  changeDialogFormVisible: false,
  loading: false,
  formData: {
    projectName: "",
    projectCode: "",
    projectId: "",
    fillMonth: "",
    detailList: []
  }
});
const projectId = ref(route.query.projectId);
const businessId = ref(route.query.id);
const nodeId = ref(route.query.nodeId || "ACT_010");
const flowId = ref(route.query.flowId || "");
const instanceId = ref(route.query.instanceId || "");
const taskId = ref(route.query.taskId || "");
const projectList = ref([]);
const formRules = ref({
  projectName: [{ required: true, message: "请选择项目", trigger: "change" }],
  fillMonth: [{ required: true, message: "请选择填报月份", trigger: "change" }]
});

const flowStartData = reactive({
  formBaseInfo: {
    billName: "",
    projectName: "",
    projectManageId: projectId,
    id: businessId,
    flowStartAttachmentArr: []
  },
  flowFormData: {
    businessId: businessId,
    flowTypeCode: "2030",
    nodeId: nodeId,
    projectManageId: projectId,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "2030",
    flowType: "2030",
    assignee: null,
    opinion: ""
  }
});

const flowPassData = reactive({
  formBaseInfo: {
    id: businessId,
    acceptUsers: null
  },
  flowFormData: {
    approvalComments: "",
    approvalResult: "",
    businessId: businessId,
    flowId: flowId,
    flowTypeCode: "2030",
    instanceId: instanceId,
    nodeId: nodeId,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "2030",
    flowType: "",
    nodeId: nodeId,
    procInstId: instanceId,
    taskId: taskId,
    opinion: "",
    assignee: null,
    isChargehand: "1", //1：向下提交到下一步：0：回退到某一步
    specialReject: "0"
  },
  tmpStorage: {
    nodeId: nodeId,
    flowId: flowId,
    taskId: taskId,
    handlerId: null,
    valueJson: ""
  }
});

const handleSubmit = async () => {
  state.saveLoading = true;
  const flag = await handleSave(false, "2");
  if (flag == null) {
    state.saveLoading = false;
    return;
  }
  if (!flag) {
    if (route.query.instanceId) {
      flowPassSubmit();
    } else {
      flowSumbitStart();
    }
  }
};

const flowSumbitStart = async () => {
  flowStartData.formBaseInfo.billName =
    state.formData.projectName + "-项目工时-审批流程";
  flowStartData.formBaseInfo.projectName = state.formData.projectName;
  const { code, message } = await flowStart(flowStartData);
  if (code === 200) {
    state.saveLoading = false;
    NotifMessage.success(message);
    goBack();
  }
};

const flowPassSubmit = async () => {
  flowPassData.flowFormData.approvalComments = "";
  flowPassData.flowFormData.approvalResult = "1"; //同意：1，不同意：0
  flowPassData.flowFormData.remarks = "";
  flowPassData.formSubMap.opinion = ``;
  flowPassData.tmpStorage.valueJson = JSON.stringify(flowPassData.formSubMap);
  const info = storageLocal.getItem("rdms-info");
  const userId = info?.userId;
  flowPassData.tmpStorage.handlerId = userId;
  flowPassData.formSubMap.isChargehand = "1";
  const { code, message } = await flowSubmit(flowPassData);
  if (code === 200) {
    NotifMessage.success(message);
    router.push("/approval/todo");
  } else {
    NotifMessage.error(message);
  }
};

//保存
const handleSave = async (flag = true, status: string): Promise<any> => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (isValid) {
    console.log(status);
    state.saveLoading = true;
    const { query } = unref(route);
    if (query.mode === "edit") {
      const { code, message } = await saveWorkingHour(state.formData);
      if (code === 200) {
        if (flag) {
          state.saveLoading = false;
          NotifMessage.success(message);
          goBack();
          return true;
        } else {
          return false;
        }
      } else {
        state.saveLoading = false;
      }
    } else {
      const { code, message, data } = await saveWorkingHour(state.formData);
      if (code === 200) {
        businessId.value = data;
        if (flag) {
          state.saveLoading = false;
          NotifMessage.success(message);
          goBack();
          return true;
        } else {
          return false;
        }
      } else {
        state.saveLoading = false;
      }
    }
  }
};

const handleSelected = item => {
  const target = projectList.value.find(el => el.id === item);
  state.formData.projectCode = target.projectCode;
  state.formData.projectName = target.projectName;
  projectId.value = item;
  initGetProjectInfo(item);
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectList({ pageNum: 1, pageSize: 0 });
    if (code === 200) {
      projectList.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

let quantityTotal = computed(() => {
  let num = 0;
  state.formData.detailList.forEach(item => {
    num += item.quantity;
  });
  return num;
});

const initWorkingHourDetails = async (id: number | string) => {
  const { code, data } = await workingHourDetails({ id });
  if (code === 200) {
    const copyFormData = cloneDeep(data);
    state.formData = copyFormData;
    const obj = projectList.value.find(
      item => item.projectCode === copyFormData.projectCode
    );
    flowStartData.formSubMap.assignee = obj.projectLeaderId + "";
    flowPassData.formBaseInfo.acceptUsers = obj.projectLeaderId + "";
    flowPassData.formSubMap.assignee = obj.projectLeaderId + "";
    projectId.value = obj.id;
    getStep();
  }
};

//获取流程转态
const getStep = () => {
  steps.value = flowStatusObj[state.flowType];
  if (steps.value && steps.value.length) {
    steps.value.forEach((item, index) => {
      if (item.nodeId === nodeId.value) {
        currentStep.value = Number(index);
      }
    });
  }
};

const initGetProjectInfo = async (id: number | string) => {
  const { code, data } = await getProjectInfo({ id });
  if (code === 200) {
    if (!instanceId.value) {
      //新增查看
      state.formData.detailList = data.projectMemberList;
      if (state.formData.detailList?.length) {
        state.formData.detailList = state.formData.detailList.map(item => {
          return {
            belongOrg: item.department,
            quantity: item.quantity || 0,
            userName: item.name,
            userId: item.userId
          };
        });
      }
    }
    flowStartData.formSubMap.assignee = data.projectLeaderId;
    flowPassData.formBaseInfo.acceptUsers = data.projectLeaderId;
    flowPassData.formSubMap.assignee = data.projectLeaderId;
  }
};

//查询流程审批记录
const getApproveHistoryList = async () => {
  const instanceId = route.query.instanceId;
  if (instanceId) {
    const { code, data } = await getApproveHistory(instanceId);
    if (code === 200) {
      approveRecord.value = data;
    }
  }
};
const goBack = (): void => {
  router.push("/project/manHour");
};

onMounted(async () => {
  const { query } = unref(route);
  if (projectId.value) {
    //驳回到第一个节点获取项目负责人
    initGetProjectInfo(projectId.value);
  }
  await getProjectList();
  if (query.id) {
    state.projectManageId = query.id as any;
    initWorkingHourDetails(query.id as string);
  }
});

// 获取项目类型
const isApproval = route.query.mode === "look" ? true : false;
const source = route.query.source;
if (route.query.instanceId) {
  getApproveHistoryList();
}
</script>

<style scoped lang="scss">
.card-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-btn {
    font-size: 14px;
    cursor: pointer;
  }
}

.btnClass {
  margin-bottom: 8px;
}

.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  overflow-x: hidden;
  overflow-y: hidden;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// #tree-option
#tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}

// #tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
#tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}

.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}

#default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

#default-option {
  padding: 0 10px;
}

.des-p {
  color: #a7a3a3;
  font-size: 12px;
}

.milepost-box {
  border: 1px solid #d8dce6;

  .milepost-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    background: #4f9dff0c;
    text-indent: 16px;
    margin-bottom: 20px;

    .close {
      position: absolute;
      right: 20px;
      top: 12px;
      color: red;
      cursor: pointer;
      font-size: 16px;
    }
  }
}

.p-text {
  line-height: 32px;
  font-size: 14px;
}

:deep .approve-code .el-form-item__content {
  margin: 0 !important;
}

.steps {
  &:deep .el-step__title {
    font-size: 12px;
    line-height: 20px;
    margin-top: 12px;
  }

  // 已完成配置
  &:deep .el-step__title.is-success {
    color: #f9b05d; // 中文字体颜色
  }

  &:deep .el-step__head.is-success {
    color: #fff; // 图标颜色

    .el-step__icon.is-text {
      border-color: #f9b05d; // 圆圈边框
      background-color: #f9b05d; // 圆框背景色
    }

    .el-step__line {
      background-color: #f9b05d; // 已完成直线颜色
    }
  }

  // 正在进行中
  &:deep .el-step__head.is-process {
    color: #f9b05d; // 图标颜色

    // color: red; // 图标颜色
    .el-step__icon.is-text {
      border-color: #f9b05d; // 圆圈边框
      background-color: #fff; // 圆框背景色
    }

    .el-step__icon-inner {
      // display: none;
      width: 16px;
      height: 16px;
      background: #f9b05d;
      border-radius: 50%;
    }
  }

  // 未执行
  &:deep .el-step__head.is-wait {
    // color: #f9b05d; // 图标颜色
    // .el-step__icon.is-text {
    //   border-color: #f9b05d; // 圆圈边框
    //   background-color: #fff; // 圆框背景色
    //
    height: 24px;

    .el-step__icon-inner {
      display: none;
    }
  }
}

.work-tips {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  color: #999;

  .total {
    margin: 0 30px;
  }

  .left {
    margin-right: 4px;
  }
}
</style>
